package net.cloudsun.graph.puzzle.relation;

import net.cloudsun.graph.puzzle.JigsawState;
import net.cloudsun.graph.puzzle.Pair;
import net.cloudsun.graph.puzzle.PuzzleDirection;
import net.cloudsun.graph.puzzle.PuzzleStateRelation;

import java.util.function.Function;

/**
 * 上滚
 * created at 25/11/2021
 *
 * @author 俞建波
 * <a href="mailto://yujianbo@chtwm.com">yujianbo@chtwm.com</a>
 * @since 1.2.0
 */
public enum UpRoll implements Function<JigsawState, JigsawState> {
    INSTANCE;

    /**
     * 总共8个位置
     * 每个位置只有一个方向。这就是顺时针旋转
     * X X X
     * X U X
     * X U X
     *
     * @param start
     * @return
     */
    @Override
    public JigsawState apply(JigsawState start) {
        // 先获取位置
        final Pair<Integer> location = PuzzleStateRelation.getLocation(start, 8);
        // 如果
        final Integer row = location.getA();
        final int[][] ints = start.toArray();
        if (row != 0) {
            PuzzleStateRelation.swap(ints, location, PuzzleDirection.UP);
            return new JigsawState(ints);
        } else {
            // 根据循环群理论，三阶循环右转一次等于左转两次，因为这这种情况不允许右转
            return DownRoll.INSTANCE.twice().apply(start);
        }
    }

    public Function<JigsawState,JigsawState> twice() {
        return this.andThen(this);
    }
}
